package com.jumper.property.comparer.diff.value;

import com.jumper.property.comparer.core.bean.PropertySetting;
import com.jumper.property.comparer.diff.Diff;
import com.jumper.property.comparer.diff.DiffVal;
import com.jumper.property.comparer.formatter.PropertyDiffFormatter;
import com.jumper.property.comparer.util.ListUtil;
import com.jumper.property.comparer.util.ValueUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 普通属性差异获取
 */
public class PropertyDiff implements Diff {

    private final PropertySetting setting;
    private final String beforeValue;
    private final String afterValue;

    public PropertyDiff(PropertySetting setting, Object beforeData, Object afterData) {
        this.setting = setting;
        this.beforeValue = ValueUtil.getStrValue(beforeData, setting.getField());
        this.afterValue = ValueUtil.getStrValue(afterData, setting.getField());
    }

    @Override
    public List<DiffVal> getDiffValues() {
        if (noChange()) {
            return new ArrayList<>();
        }
        return ListUtil.toList(new DiffVal(
                beforeValue, afterValue, getDiffValue()
        ));
    }

    private boolean noChange() {
        return Objects.equals(beforeValue, afterValue);
    }

    private String getDiffValue() {
        return new PropertyDiffFormatter(setting.getPropertyName(), beforeValue, afterValue).format();
    }
}
